const login = document.querySelector('.login')
const register = document.querySelector('.register')

// 点击切换注册和登录盒子的显示与隐藏
document.querySelector('.goRegister').addEventListener("click", () => {
    login.style.display = 'none'
    register.style.display = 'block'
})
document.querySelector('.goLogin').addEventListener('click', () => {
    login.style.display = 'block'
    register.style.display = 'none'
})

// 点击登录事件
document.querySelector('.login .btn-primary').addEventListener('click', async e => {
    const username = document.querySelector('.login [name=username]').value
    const password = document.querySelector('.login [name=password]').value
    e.preventDefault()
    if (username.length < 2 || username.length > 15) {
        return alert('请输入正确的用户名')
    }
    if (password.length < 6 || password.length > 15) {
        return alert('请输入正确的密码')
    }
    const res = await axios({
        url: "/api/login",
        method: 'post',
        data: {
            username,
            password
        }
    })
    console.log(res.data);
    localStorage.setItem('mytoken', res.data.token)
    localStorage.setItem('username', username)
    location.href = './index.html'
})

// 点击注册事件
document.querySelector('.register .btn-primary').addEventListener('click', async e => {
    const username = document.querySelector('.register [name=username]').value
    const password = document.querySelector('.register [name=password]').value
    e.preventDefault()
    if (username.length < 2 || username.length > 15) {
        return alert('用户名为长度2~15位')
    }
    if (password.length < 6 || password.length > 15) {
        return alert('密码为长度6~15位')
    }
    const res = await axios({
        url: "/api/register",
        method: 'post',
        data: {
            username,
            password
        }
    })
    console.log(res);
})